<?php
/*
 * Member System For Codeigniter
 * Powered By BeYourCyber
 * First Create 28/08/2009
 * 
 * document seedetail at XXX/sys/document
 */
class Mem extends Controller {

	function Mem()
	{
		parent::Controller();	
		$this->load->library('Member');
		$this->load->library('Bee');
		$this->load->helper('url');
	}
	
	function index()
	{
		$this->load->view('mem/index');
	}
	
	function admin()
	{
		$this->load->database();
		$this->load->model('mem/mem_m');
		$this->load->library('Authen');
		// get action //
		$zone = $this->uri->segment(3);
		$cf		= $this->member->memconfig();
		// get action //
		
		switch($zone){
			/******** Admin Panel *******/
			case "panel":
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$this->load->view('mem/a_index_v',$data);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******** Admin Panel *******/
			
			/******** View Member *******/
			case "viewmember":
				if($this->authen->checkAdmin()){
					$this->load->library('pagination');
					$data['cf'] = $cf;
					//count all member
					$data['countmember'] 	= ($this->mem_m->countMember())+1;
					$data['perpage']		= 50;
					
					if($this->uri->segment(4) && preg_match( '/^[0-9]+$/', $this->uri->segment(4))){
						$page 			= $this->uri->segment(4);
						$data['mem']	= $this->mem_m->a_50mem($page,$data['perpage']);
					}
					else
					{
						$data['mem']	= $this->mem_m->a_50mem(0,$data['perpage']);
					}
					$this->load->view('mem/a_viewmember_v',$data);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******** View Member *******/
			
			/******** Add Member *******/
			case "add":
				/*
				 * 1. input [user][password][email]
				 * 2. send email to that user (for activate)
				 * 3. user login to activate and input fill form personal data
				 * 4. submit to complete flow
				 */
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$this->load->library('form_validation');
					$this->load->library('Securimage');
					$this->load->library('session');
					
					$config = array(
		               array(
                     'field'   => 'username', 
                     'label'   => 'Username', 
                     'rules'   => 'required|alpha_dash|min_length[2]|max_length[24]'
                  ),
		               array(
                     'field'   => 'password', 
                     'label'   => 'Password', 
                     'rules'   => 'required|min_length[5]|max_length[25]'
                  ),
		               array(
		                     'field'   => 'confirmpassword', 
		                     'label'   => 'Password Confirmation', 
		                     'rules'   => 'required'
		                  ),   
		               array(
                     'field'   => 'email', 
                     'label'   => 'Email', 
                     'rules'   => 'required|min_length[9]|max_length[70]|valid_email'
                  )
		            );
		
					$this->form_validation->set_rules($config);
					
					if ($this->form_validation->run() == FALSE)
                    {
                    	$this->load->view('mem/a_adduser_v',$data);
                    }
                    else
                    {
                    	foreach (explode(' ', 'username password confirmpassword email p_images userrank') as $v)
	                    {
	                        $datainput[$v] = $this->input->post($v);
	                    }

						/// record to database ///
						$userid = $this->mem_m->addUserActivate($datainput);
						/// record to database ///
						
						$linkdata = $this->bee->simpleEncrypt($userid);
						
                    	/// send email
						//send email to this member
						$this->load->library('phpmailer');
			            $this->phpmailer->IsSendmail();
			            $this->phpmailer->AddReplyTo($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->SetFrom($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->AddAddress($datainput['email'], $datainput['username']);
			            $this->phpmailer->Subject = "Account wait for activate FROM ".$cf['systemname'];
			            $this->phpmailer->MsgHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			    	<html xmlns="http://www.w3.org/1999/xhtml">
			    	<head>
			    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			    	<title>Your account wait for activate @ '.$cf["systemname"].'</title>
			    	</head>
			    	
			    	<body>
			    	<p>Please click link for activate your account and full fill form.</p>
					<p>You can click via '.base_url().'mem/sys/activate/'.$linkdata.'</p>
					<p>Username : '.$datainput['username'].'<br />
					Email    : '.$datainput['email'].'<br />
					Password : '.$datainput['password'].'
					</p>
			    	</body>
			    	</html>');
			            if (!$this->phpmailer->Send())
			            {
			                $tmp = "Mailer Error: ".$this->phpmailer->ErrorInfo;
			                mail($cf['emailsystem'], 'mail error FROM '.$cf['systemname'], $tmp);
			
			            } else
			            {
							$data['complete'] = TRUE;
							$data['link'] = base_url()."mem/sys/activate/".$linkdata;
							$this->load->view('mem/a_adduser_v',$data);
						}
						/// send email
					}				
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******** Add Member *******/
			
			/******** Edit Member *******/
			case "editmember":
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$userid = $this->uri->segment(4);
					$this->load->library('form_validation');
                    // รับค่าทั้งหมด //
                    $cf['username'] = $cf['password'] = $cf['confirmpassword'] = $cf['email'] = TRUE;
                    foreach (explode(' ', 'p_name p_surname p_gender p_birthdate p_married p_address p_city p_state p_zip p_country p_telephone p_mobilephone p_fax p_job p_msn p_hi5 p_facebook p_twitter p_url p_income p_internet p_family p_personalid p_emailnews p_type') as $v)
                    {
                        if ($cf[$v])
                        {
                            $datainput[$v] = $this->input->post($v);
            
                        }
                    }
                    $data = $datainput;
                    // รับค่าทั้งหมด //
                    $data['cf'] = $cf;
					$config = $this->member->Set_ruleeditprofile();
                    $this->form_validation->set_rules($config);
                    if ($this->form_validation->run() == FALSE)
                    {
                    	$data['init'] = $this->authen->init();
            			$data = $this->mem_m->profileEdit($userid);
                    	$data['cf'] = $cf;
                        $this->load->view('mem/a_editprofile_v', $data);
                    }
                    else
                    {
                    	
                    	// record to database //
						$this->mem_m->updateProfile($datainput,$userid);
						// record to database //
						$data['profile']	= $this->mem_m->a_loadProfile($userid);
	
						$this->load->view('mem/a_viewprofile_v',$data);
                    }
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
				
			case "updatestatus":
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$userid = $this->uri->segment(4);
					$value = $this->input->post('act_value');
					$s = "UPDATE ".$cf['table_usersystem']." SET userstatus = ".$value." WHERE id=".$userid." AND id != 1";
					mysql_query($s);
					echo $this->member->SetUserStatus($value);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			case "updaterank":
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$userid = $this->uri->segment(4);
					$value = $this->input->post('act_value');
					$s = "UPDATE ".$cf['table_usersystem']." SET userrank = ".$value." WHERE id=".$userid." AND id != 1";
					mysql_query($s);
					echo $this->member->SetUserRank($value);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******** Edit Member *******/
			
			
			/******** Member Detail *******/
			case "memberdetail":
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$id = $this->uri->segment(4);
					$data['profile']	= $this->mem_m->a_loadProfile($id);

					$this->load->view('mem/a_viewprofile_v',$data);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******** Admin Panel *******/
			
			
			case "edit":
				$this->load->view('mem/loginbox_v');
				break;
			case "deletemember":
				if($this->authen->checkAdmin()){
					$data['cf'] = $cf;
					$user['userid'] = $this->uri->segment(4);
					$this->mem_m->deleteUser($user);

					redirect('/mem/admin/viewmember');
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
				
			/******* SEARCH ******/
			case "search":
				if($this->authen->checkAdmin()){
					$this->load->library('form_validation');
					$data['cf'] = $cf;
					$this->form_validation->set_rules('search', 'Search', 'required|min_length[2]');
					if ($this->form_validation->run() == FALSE)
					{
						redirect('mem/admin/viewmember');
					}
					else
					{
						$keyword = $this->input->post('search');
						$data['mem']	= $this->mem_m->searchMember($keyword);
						$this->load->view('mem/a_viewsearch_v',$data);
					}
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******* SEARCH ******/
			
			/******* member report ******/
			case "memberreport":
				$this->load->library('graph');
				$this->load->library('graph_obj');
				if($this->authen->checkAdmin()){
					//นับจำนวนสมาชิกทั้งหมด 
					$data['counts'] = $this->mem_m->countMemberReport();
					
					//ช่วงเวลาที่สมัคร  [today][yesterday][thismonth][lastmonth][thisyear][lastyear]
					$data['inperiod'] = $this->mem_m->countPeriod();
					
					//
					// load view report
					//
					if($this->uri->segment(4)){
						switch($this->uri->segment(4)){
						case "today";
							$bar_1 = new bar_glass( 50, '#D54C78', '#C31812' );
							$bar_1->key( 'register', 8 );
							$bar_1->data[] = $data['inperiod']['yesterday'];
							$bar_1->data[] = $data['inperiod']['today'];
	
							//
							// create the chart:
							//
							$g = new graph();
							$g->title( 'today and yesterday', '{font-size:14px; color: #bcd6ff; margin:10px; background-color: #5E83BF; padding: 5px 15px 5px 15px;}' );
							
							// add both sets of bars:
							$g->data_sets[] = $bar_1;
							
							// label the X axis (10 labels for 10 bars):
							$g->set_x_labels( array( 'yesterday','today' ) );
							
							// colour the chart to make it pretty:
							$g->x_axis_colour( '#909090', '#D2D2FB' );
							$g->y_axis_colour( '#909090', '#D2D2FB' );
							
							$g->set_y_min( 0 );
							if($data['inperiod']['today']>=$data['inperiod']['yesterday']){
								$g->set_y_max( $data['inperiod']['today'] );
							}
							else
							{
								$g->set_y_max( $data['inperiod']['yesterday'] );
							}
							$g->y_label_steps( 2 );
							$g->set_y_legend( 'member(s)', 12, '#736AFF' );
							echo $g->render();
								break;
						
						case "thismonth":
							$bar_1 = new bar_glass( 50, '#D54C78', '#C31812' );
							$bar_1->key( 'register', 8 );
							$bar_1->data[] = $data['inperiod']['lastmonth'];
							$bar_1->data[] = $data['inperiod']['thismonth'];
	
							//
							// create the chart:
							//
							$g = new graph();
							$g->title( 'this month and last month', '{font-size:14px; color: #bcd6ff; margin:10px; background-color: #5E83BF; padding: 5px 15px 5px 15px;}' );
							
							// add both sets of bars:
							$g->data_sets[] = $bar_1;
							
							// label the X axis (10 labels for 10 bars):
							$g->set_x_labels( array( 'lastmonth','thismonth' ) );
							
							// colour the chart to make it pretty:
							$g->x_axis_colour( '#909090', '#D2D2FB' );
							$g->y_axis_colour( '#909090', '#D2D2FB' );
							
							$g->set_y_min( 0 );
							if($data['inperiod']['thismonth']>=$data['inperiod']['lastmonth']){
								$g->set_y_max( $data['inperiod']['thismonth'] );
							}
							else
							{
								$g->set_y_max( $data['inperiod']['lastmonth'] );
							}
							$g->y_label_steps( 2 );
							$g->set_y_legend( 'member(s)', 12, '#736AFF' );
							echo $g->render();
							break;
							case "thisyear":
								$bar_1 = new bar_glass( 50, '#D54C78', '#C31812' );
								$bar_1->key( 'register', 8 );
								$bar_1->data[] = $data['inperiod']['lastyear'];
								$bar_1->data[] = $data['inperiod']['thisyear'];
		
								//
								// create the chart:
								//
								$g = new graph();
								$g->title( 'this year and last year', '{font-size:14px; color: #bcd6ff; margin:10px; background-color: #5E83BF; padding: 5px 15px 5px 15px;}' );
								
								// add both sets of bars:
								$g->data_sets[] = $bar_1;
								
								// label the X axis (10 labels for 10 bars):
								$g->set_x_labels( array( 'lastyear','thisyear' ) );
								
								// colour the chart to make it pretty:
								$g->x_axis_colour( '#909090', '#D2D2FB' );
								$g->y_axis_colour( '#909090', '#D2D2FB' );
								
								$g->set_y_min( 0 );
								if($data['inperiod']['thisyear']>=$data['inperiod']['lastyear']){
									$g->set_y_max( $data['inperiod']['thisyear'] );
								}
								else
								{
									$g->set_y_max( $data['inperiod']['lastyear'] );
								}
								$g->y_label_steps( 2 );
								$g->set_y_legend( 'member(s)', 12, '#736AFF' );
								echo $g->render();
								break;
							case "userstate":
								$g = new graph();
								
								while($t = mysql_fetch_assoc($data['counts'])){
									$datagraph[] = $t['count'];
									$dataindex[] = $this->member->SetUserStatus($t['userstatus']);
								}

								//
								// PIE chart, 60% alpha
								//
								$g->pie(60,'#505050','{font-size: 12px; color: #404040;');
								//
								// pass in two arrays, one of data, the other data labels
								//
								//print_r($datagraph);
								//print_r($dataindex);
								$g->pie_values( $datagraph, $dataindex );
								//
								// Colours for each slice, in this case some of the colours
								// will be re-used (3 colurs for 5 slices means the last two
								// slices will have colours colour[0] and colour[1]):
								//
								$g->pie_slice_colours( array('#d01f3c','#356aa0','#C79810') );
								
								$g->set_tool_tip( '#val#' );
								
								$g->title( 'Member state', '{font-size:18px; color: #d01f3c}' );
								echo $g->render();
								break;
							default:
								break;
						}
					}
					else
					{
						//load view member report
						$this->load->view('mem/a_memberreport_v',$data);
					}
					
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******* member report ******/
							
			default:
				$this->load->view('mem/index');
		}
	}
	
	function sys()
	{
		// get action //
		$zone 	= $this->uri->segment(3);
		$cf		= $this->member->memconfig();
		// get action //
		
		
		switch($zone){
			
			/******* REGISTER ********/
			case "register":
				
				if($cf['emailconfirm']){
					redirect('/mem/sys/signup');
					exit(); //เลิกการทำงานเนื่องจากต้อง confirm email ด้วย ให้เรียก signup แทน
				}
				$this->load->library('form_validation');
				$this->load->library('Securimage');
				$this->load->library('session');
				
				///upload configuration
			            $config['upload_path'] = './upload/memupload/';
			            $config['allowed_types'] = 'gif|jpg';
			            $config['max_size'] = '500';
			            $config['max_width'] = '2048';
			            $config['max_height'] = '2048';
			            $config['encrypt_name'] = TRUE;
			            $config['remove_spaces'] = TRUE;
			            $this->load->library('upload', $config);
				
				$config = $this->member->Set_rulesignup();
				$this->form_validation->set_rules($config);
				// รับค่าทั้งหมด //
				$cf['username'] = $cf['password'] = $cf['confirmpassword'] = $cf['email'] = TRUE;
		        foreach (explode(' ', 'username password confirmpassword email p_name p_surname p_gender p_birthdate p_married p_address p_city p_state p_zip p_country p_telephone p_mobilephone p_fax p_job p_msn p_hi5 p_facebook p_twitter p_url p_income p_internet p_family p_personalid p_emailnews p_type') as $v){
		        	if($cf[$v])
					{
						$datainput[$v] = $this->input->post($v);
						
					}
		        }
				$data = $datainput;
		        // รับค่าทั้งหมด //
				$data['cf']	= $cf;
				if ($this->form_validation->run() == FALSE)
				{
					
					$this->load->view('mem/regisform_v',$data);
				}
				else
				{
					if(!$this->securimage->check($this->input->post('p_images'))){
						die('securecode wrong');
					}
					$this->load->model('mem/mem_m');
					$this->load->database();
					// upload avatar //
					if($cf['p_avatar'] && $cf['re_p_avatar'])
					{
						
						
						if ($this->upload->do_upload('p_avatar'))
                		{
                			//upload รูปผ่าน
		                    $dataupload = $this->upload->data();
		                    $this->load->library('image_lib');
		    
		                    $config['image_library'] = 'GD2';
		                    $config['source_image'] = $dataupload['full_path'];
		                    $config['new_image'] = $dataupload['full_path'];
		                    //upload รูปผ่าน
		                    $datainput['p_avatar'] = $dataupload['file_name'];
		    
		                    // crop image set to center //
		                    if ($dataupload['image_width'] > $dataupload['image_height'])
		                    { // Landscape: Crop left & right
		                        $config['width'] = $dataupload['image_height'];
		                        $config['height'] = $dataupload['image_height'];
		                        $config['x_axis'] = ($dataupload['image_width']-$config['width'])/2;
		                    }
		                    else
		                    { // Portrait: crop top & bottom
		                        $config['width'] = $dataupload['image_width'];
		                        $config['height'] = $dataupload['image_width'];
		                        $config['y_axis'] = ($dataupload['image_height']-$config['height'])/2;
		                    }
		                    $config['maintain_ratio'] = false;
		                    $this->image_lib->initialize($config);
		    
		                    if (!$this->image_lib->crop())
		                    {
		                        show_error($this->image_lib->display_errors());
		                    }
		    
		                    // Clear lib so we can do some more image processing
		                    $this->image_lib->clear();
		                    // crop image set to center //
		    
		                    //create thumbnail
		    
		                    $config['image_library'] = 'GD2';
		                    $config['source_image'] = $dataupload['full_path'];
		                    $config['new_image'] = $dataupload['full_path'];
		                    $config['quality'] = '75%';
		                    $config['master_dim'] = 'width';
		                    $config['width'] = 150;
		                    $config['height'] = 150;
		    
		                    $this->image_lib->initialize($config);
		                    if (!$this->image_lib->resize())
		                    {
		                        echo $this->image_lib->display_errors();
		                    }
		                    $this->image_lib->clear();
							
							// record to database //
							$this->mem_m->signupUser($datainput);
							// record to database //
							$datainput['datainput'] = $datainput;
							$this->load->view('mem/formsuccess_v',$datainput);
						}
						else
						{
							//upload รูปไม่ผ่าน
							$this->load->view('mem/regisform_v',$data);
						}
					}
					elseif($cf['p_avatar'] && !$cf['re_p_avatar'])
					{
						//มีหรือไม่มีส่วน avatar
						///upload configuration
			            $config['upload_path'] = './upload/memupload/';
			            $config['allowed_types'] = 'gif|jpg';
			            $config['max_size'] = '500';
			            $config['max_width'] = '2048';
			            $config['max_height'] = '2048';
			            $config['encrypt_name'] = TRUE;
			            $config['remove_spaces'] = TRUE;
			            $this->load->library('upload', $config);
						
						if ($this->upload->do_upload('p_avatar'))
                		{
                			//upload รูปผ่าน
		                    $dataupload = $this->upload->data();
		                    $this->load->library('image_lib');
		    
		                    $config['image_library'] = 'GD2';
		                    $config['source_image'] = $dataupload['full_path'];
		                    $config['new_image'] = $dataupload['full_path'];
		                    //upload รูปผ่าน
		                    $datainput['p_avatar'] = $dataupload['file_name'];
		    
		                    // crop image set to center //
		                    if ($dataupload['image_width'] > $dataupload['image_height'])
		                    { // Landscape: Crop left & right
		                        $config['width'] = $dataupload['image_height'];
		                        $config['height'] = $dataupload['image_height'];
		                        $config['x_axis'] = ($dataupload['image_width']-$config['width'])/2;
		                    }
		                    else
		                    { // Portrait: crop top & bottom
		                        $config['width'] = $dataupload['image_width'];
		                        $config['height'] = $dataupload['image_width'];
		                        $config['y_axis'] = ($dataupload['image_height']-$config['height'])/2;
		                    }
		                    $config['maintain_ratio'] = false;
		                    $this->image_lib->initialize($config);
		    
		                    if (!$this->image_lib->crop())
		                    {
		                        show_error($this->image_lib->display_errors());
		                    }
		    
		                    // Clear lib so we can do some more image processing
		                    $this->image_lib->clear();
		                    // crop image set to center //
		    
		                    //create thumbnail
		    
		                    $config['image_library'] = 'GD2';
		                    $config['source_image'] = $dataupload['full_path'];
		                    $config['new_image'] = $dataupload['full_path'];
		                    $config['quality'] = '75%';
		                    $config['master_dim'] = 'width';
		                    $config['width'] = 150;
		                    $config['height'] = 150;
		    
		                    $this->image_lib->initialize($config);
		                    if (!$this->image_lib->resize())
		                    {
		                        echo $this->image_lib->display_errors();
		                    }
		                    $this->image_lib->clear();
							
							// record to database //
							$this->mem_m->signupUser($datainput);
							// record to database //
							$datainput['datainput'] = $datainput;
							$this->load->view('mem/formsuccess_v',$datainput);
						}
						else
						{
							$datainput['p_avatar'] = "";
							// record to database //
							$this->mem_m->signupUser($datainput);
							// record to database //
							$datainput['datainput'] = $datainput;
							$this->load->view('mem/formsuccess_v',$datainput);
						}
					}
					else
					{
						$datainput['p_avatar'] = "";
							// record to database //
							$this->mem_m->signupUser($datainput);
							// record to database //
							$datainput['datainput'] = $datainput;
							$this->load->view('mem/formsuccess_v',$datainput);
					}
					// upload avatar //
				}
				
				break;
			/******* REGISTER ********/
			case "showimage":
				$this->load->library('Securimage');
				$this->load->library('session');
				$this->securimage->show();
				break;
				
			/******* LOGIN ********/	
			case "login":
				$this->load->library('form_validation');
				$this->load->library('Authen');
				
				$data['cf'] = $cf;
				$config = $this->member->Set_rulelogin();
				$this->form_validation->set_rules($config);
				
				if ($this->form_validation->run() == FALSE)
				{
					$this->load->view('mem/loginbox_v',$data);					
				}
				else
				{
					
					$this->load->database();
					$this->load->model('mem/mem_m');
					$password  		= $this->input->post('password');
					if($cf['whatlogin']=='user'){
						$username 	= $this->input->post('username');
						if($this->mem_m->loginUser($username,$password)){
							//login ok write authen
							$userid = $this->mem_m->useridFromUser($username);
							$this->authen->writeAuthen($username,$password,$userid);
							redirect('/mem/user/panel');
						}
						else
						{
							$data['errormsg'] = "ข้อมูลที่กรอกไม่ถูกต้อง หรือ Account ถูกระงับการใช้งาน";
							$this->load->view('mem/loginbox_v',$data);
						}
					}
					else
					{
						$email		= $this->input->post('email');	
						if($this->mem_m->loginEmail($email,$password)){
							//login ok write authen
							$data = $this->mem_m->useridFromEmail($email);
							$this->authen->writeAuthen($data['username'],$password,$data['id']);
							redirect('/mem/user/panel');
						}
						else
						{
							$data['errormsg'] = "ข้อมูลที่กรอกไม่ถูกต้อง หรือ Account ถูกระงับการใช้งาน";
							$this->load->view('mem/loginbox_v',$data);
						}
					}
				}
				
				break;
			/******* LOGIN ********/	
			
			/******* FORGOT PASSWORD ********/	
			case "forgotpassword":
				$this->load->library('Securimage');
				$this->load->library('session');
				$this->load->library('form_validation');
				$this->load->database();
				$this->load->model('mem/mem_m');
				
				$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
				if ($this->form_validation->run() == FALSE)
				{
					$this->load->view('mem/forgotform_v');					
				}
				else
				{
					$email = $this->input->post('email');
					$data = $this->mem_m->forgotPassword($email);
					if($data[0]){
						//ทำการ generate new password
						$this->load->library('Authen');
						$this->load->library('Bee');
						
						$tmppass = $newpass = $this->bee->passwdgen(8);
						$newpass = $this->authen->hashpass($newpass);
						
						//update new password to this member
						$userid = $this->mem_m->useridFromEmail($email);
						$this->mem_m->updatePassword($userid,$newpass);
						
						//send email to this member
						$this->load->library('phpmailer');
			            $this->phpmailer->IsSendmail();
			            $this->phpmailer->AddReplyTo($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->SetFrom($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->AddAddress($email, $data[0]);
			            $this->phpmailer->Subject = "Forgot Password FROM ".$cf['systemname'];
			            $this->phpmailer->MsgHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			    	<html xmlns="http://www.w3.org/1999/xhtml">
			    	<head>
			    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			    	<title>Forgot Password FROM '.$cf["systemname"].'</title>
			    	</head>
			    	
			    	<body>
			    	<p>You have or someone has requested a new password to access your account.\n
Your new password is : <b>'.$tmppass.'</b></p>
					<p>You can login via '.base_url().'mem/sys/login</p>
			    	</body>
			    	</html>');
			            if (!$this->phpmailer->Send())
			            {
			                $tmp = "Mailer Error: ".$this->phpmailer->ErrorInfo;
			                mail($cf['emailsystem'], 'mail error FROM '.$cf['systemname'], $tmp);
			
			            } else
			            {
							$data['complete'] = TRUE;
							$this->load->view('mem/forgotform_v',$data);
						}
						
						
					}
					else
					{
						header ('Content-type: text/html; charset=utf-8');
						echo "email not have in database , Email นี้ไม่มีอยู่ในระบบ";
					}
				}
				break;
			/******* FORGOT PASSWORD ********/	
			
			
			case "logout":
				$this->load->library('Authen');
				$this->authen->logout();
				redirect('/mem/sys/login');
				break;
			case "document":
				$this->load->view('mem/document_v');
				break;
			case "install":
				$this->load->database();
				$this->load->model('mem/mem_install_m');
				if($this->mem_install_m->installed()){
					header ('Content-type: text/html; charset=utf-8');
					echo "member system installed if you want to install again please delete table first(see table name in config file) - ระบบติดตั้งเรียบร้อยแล้ว ถ้าต้องการติดตั้งใหม่ ให้ทำการลบ table ออกก่อน (ดูชื่อ table ใน config file)";
				}
				else
				{
					$this->mem_install_m->doinstall();
					echo "Install DONE!!";
				}	
				break;
			
			/******* updateamphur ********/
       		case "updateamphur" : 
				$this->load->database();
				$this->load->library('form_validation');
				$config = array(array('field'=>'province', 'label'=>'จังหวัด', 'rules'=>'required|is_natural_no_zero'));
                $this->form_validation->set_rules($config);
                $provinceid = $this->input->post('province');
                if ($this->form_validation->run() == FALSE) {
                
                } else {
                    //update map
                    $amphur = $this->bee->Get_amphurname($provinceid,'0');
                    echo '<select name="p_city" id="p_city">';
                    echo '<option value="" selected="selected">== เลือกอำเภอ/เขต  ==</option>';
                    foreach($amphur as $k => $v){
                        echo '<option value="'.$k.'">'.$v.'</option>';
                    }
                    echo '</select>';
                }
                break;
			/******* updateamphur ********/
			
			/******* checkdupusername ********/
			case "checkdupusername":
				$this->load->database();
				$this->load->library('form_validation');
				$this->load->model('mem/mem_m');
            $config = array(array('field'=>'usr', 'label'=>'ชื่ีอ username', 'rules'=>'required|alpha_dash|min_length[2]|max_length[24]'));
            $this->form_validation->set_rules($config);
            $provinceid = $this->input->post('province');
            if ($this->form_validation->run() == FALSE) {
                echo "<span style=\"color:#CC0033;\">username นี้ไม่สามารถใช้งานได้</span>";
            } else {
                //check username from database
                $username = $this->input->post('usr');
                if ($this->mem_m->checkUsernamedup($username)) {
                    echo "<span style=\"color:#CC0033;\">username นี้ไม่สามารถใช้งานได้</span>";
                } else {
                    echo "<span style=\"color:#339900;\">username นี้สามารถใช้งานได้</span>";
                }
            }

				break;
			/******* checkdupusername ********/
			
			/******* checkdupemail ********/
			case "checkdupemail":
				$this->load->database();
				$this->load->library('form_validation');
				$this->load->model('mem/mem_m');
            $config = array(array('field'=>'email', 'label'=>'Email', 'rules'=>'required|min_length[9]|max_length[70]|valid_email'));
            $this->form_validation->set_rules($config);
            $email = $this->input->post('email');
            if ($this->form_validation->run() == FALSE) {
                echo "<span style=\"color:#CC0033;\">email นี้ไม่สามารถใช้งานได้</span>";
            } else {
                //check email from database
                if ($this->mem_m->checkEmaildup($email)) {
                    echo "<span style=\"color:#CC0033;\">email นี้ไม่สามารถใช้งานได้</span>";
                } else {
                    echo "<span style=\"color:#339900;\">email นี้สามารถใช้งานได้</span>";
                }
            }

				break;	
			/******* checkdupemail ********/
			
			/******* Signup for Active ********/
			case "signup":
				$this->load->library('Authen');
				$this->load->database();
				$this->load->model('mem/mem_m');

				
					$data['cf'] = $cf;
					$this->load->library('form_validation');
					$this->load->library('Securimage');
					$this->load->library('session');
					
					$config = array(
		               array(
                     'field'   => 'username', 
                     'label'   => 'Username', 
                     'rules'   => 'required|alpha_dash|min_length[2]|max_length[24]'
                  ),
		               array(
                     'field'   => 'password', 
                     'label'   => 'Password', 
                     'rules'   => 'required|min_length[5]|max_length[25]'
                  ),
		               array(
		                     'field'   => 'confirmpassword', 
		                     'label'   => 'Password Confirmation', 
		                     'rules'   => 'required'
		                  ),   
		               array(
                     'field'   => 'email', 
                     'label'   => 'Email', 
                     'rules'   => 'required|min_length[9]|max_length[70]|valid_email'
                  )
		            );
		
					$this->form_validation->set_rules($config);
					
					if ($this->form_validation->run() == FALSE)
                    {
                    	$this->load->view('mem/signup_v',$data);
                    }
                    else
                    {
                    	foreach (explode(' ', 'username password confirmpassword email p_images') as $v)
	                    {
	                        $datainput[$v] = $this->input->post($v);
	                    }
						$datainput['userrank'] = 60;

						
						/// record to database ///
						$userid = $this->mem_m->addUserActivate($datainput);
						/// record to database ///
						
						$linkdata = $this->bee->simpleEncrypt($userid);
						
                    	/// send email
						//send email to this member
						$this->load->library('phpmailer');
			            $this->phpmailer->IsSendmail();
			            $this->phpmailer->AddReplyTo($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->SetFrom($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->AddAddress($datainput['email'], $datainput['username']);
			            $this->phpmailer->Subject = "Account wait for activate FROM ".$cf['systemname'];
			            $this->phpmailer->MsgHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			    	<html xmlns="http://www.w3.org/1999/xhtml">
			    	<head>
			    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			    	<title>Your account wait for activate @ '.$cf["systemname"].'</title>
			    	</head>
			    	
			    	<body>
			    	<p>Please click link for activate your account and full fill form.</p>
					<p>You can click via '.base_url().'mem/sys/activate/'.$linkdata.'</p>
					<p>Username : '.$datainput['username'].'<br />
					Email    : '.$datainput['email'].'<br />
					Password : '.$datainput['password'].'
					</p>
			    	</body>
			    	</html>');
			            if (!$this->phpmailer->Send())
						//if(0)
			            {
			                $tmp = "Mailer Error: ".$this->phpmailer->ErrorInfo;
			                mail($cf['emailsystem'], 'mail error FROM '.$cf['systemname'], $tmp);
			
			            } else
			            {
							$data['complete'] = TRUE;
							$data['link'] = base_url()."mem/sys/activate/".$linkdata;
							$this->load->view('mem/signup_v',$data);
						}
						/// send email
					}				

				break;
			/******* Signup for Active ********/
			
			/******* Activate Member ********/
			case "activate":
				$this->load->library('form_validation');
				$this->load->database();
				$this->load->model('mem/mem_m');
				$this->load->library('Authen');
				$this->load->library('Securimage');
				$this->load->library('session');
				
				// check ก่อนว่า สถานะคือ wait for activate
				// get user id //
				$userid = $this->uri->segment(4);
				$userid = $this->bee->simpleDecrypt($userid);
				// get user id //

				if($this->mem_m->checkWaitActive($userid)){
					//login ผ่าน ก็ให้ activate
					$config = $this->member->Set_rulelogin();
					$this->form_validation->set_rules($config);
					
					if ($this->form_validation->run() == FALSE)
					{
						$data['cf'] = $cf;
						$this->load->view('mem/activate_v',$data);					
					}
					else
					{
						if(!$this->securimage->check($this->input->post('p_images'))){
							die('securecode wrong');
						}
						$password  		= $this->input->post('password');
						if($cf['whatlogin']=='user'){ // login ด้วย user หรือ email
							$username 	= $this->input->post('username');
							if($this->mem_m->loginUser($username,$password)){
								//login ok write authen
								$userid = $this->mem_m->useridFromUser($username);
								////Show fill form
								/////$this->mem_m->activeMember($userid);
								$this->authen->writeAuthen($username,$password,$userid);
								redirect('/mem/sys/formactive');
							}
							else
							{
								$data['errormsg'] = "Username หรือ Password ไม่ถูกต้อง";
								$this->load->view('mem/activate_v',$data);
							}
						}
						else
						{
							$email		= $this->input->post('email');	
							if($this->mem_m->loginEmail($email,$password)){
								//login ok write authen
								$data = $this->mem_m->useridFromEmail($email);
								////Show fill form
								////$this->mem_m->activeMember($userid);
								$this->authen->writeAuthen($data['username'],$password,$data['id']);
								redirect('/mem/sys/formactive');
							}
							else
							{
								$data['errormsg'] = "Email หรือ Password ไม่ถูกต้อง";
								$this->load->view('mem/activate_v',$data);
							}
						}
					}
				}
				else
				{
					redirect('/mem/sys/login'); //เป็นสมาชิกอยู่แล้ว
				}

				break;
			/******* Activate Member ********/
			
			/******* Form for activate member ********/
			case "formactive":
				$this->load->library('Authen');
				$mem = $this->authen->init();
				
				$this->load->database();
				$this->load->model('mem/mem_m');
				if($this->mem_m->checkWaitActive($mem['userid'])){
					$this->load->library('form_validation');
					$this->load->library('Securimage');
					$this->load->library('session');
					
					///upload configuration
				            $config['upload_path'] = './upload/memupload/';
				            $config['allowed_types'] = 'gif|jpg';
				            $config['max_size'] = '500';
				            $config['max_width'] = '2048';
				            $config['max_height'] = '2048';
				            $config['encrypt_name'] = TRUE;
				            $config['remove_spaces'] = TRUE;
				            $this->load->library('upload', $config);
					
					$config = $this->member->Set_ruleeditprofile();
					$this->form_validation->set_rules($config);
					// รับค่าทั้งหมด //
			        foreach (explode(' ', 'p_name p_surname p_gender p_birthdate p_married p_address p_city p_state p_zip p_country p_telephone p_mobilephone p_fax p_job p_msn p_hi5 p_facebook p_twitter p_url p_income p_internet p_family p_personalid p_emailnews p_type') as $v){
			        	if($cf[$v])
						{
							$datainput[$v] = $this->input->post($v);
						}
			        }
					$data = $datainput;
			        // รับค่าทั้งหมด //
					$data['cf']	= $cf;
					if ($this->form_validation->run() == FALSE)
					{
						
						$this->load->view('mem/activeform_v',$data);
					}
					else
					{
						///ถ้าโค้ดที่กรอกผิดให้หยุดทำงาน
						if(!$this->securimage->check($this->input->post('p_images'))){
							die('securecode wrong');
						}
						// upload avatar //
						if($cf['p_avatar'] && $cf['re_p_avatar'])
						{
							//กรณีบังคับ upload avatar
							if ($this->upload->do_upload('p_avatar'))
	                		{
	                			//upload รูปผ่าน
			                    $dataupload = $this->upload->data();
			                    $this->load->library('image_lib');
			    
			                    $config['image_library'] = 'GD2';
			                    $config['source_image'] = $dataupload['full_path'];
			                    $config['new_image'] = $dataupload['full_path'];
			                    //upload รูปผ่าน
			                    $datainput['p_avatar'] = $dataupload['file_name'];
			    
			                    // crop image set to center //
			                    if ($dataupload['image_width'] > $dataupload['image_height'])
			                    { // Landscape: Crop left & right
			                        $config['width'] = $dataupload['image_height'];
			                        $config['height'] = $dataupload['image_height'];
			                        $config['x_axis'] = ($dataupload['image_width']-$config['width'])/2;
			                    }
			                    else
			                    { // Portrait: crop top & bottom
			                        $config['width'] = $dataupload['image_width'];
			                        $config['height'] = $dataupload['image_width'];
			                        $config['y_axis'] = ($dataupload['image_height']-$config['height'])/2;
			                    }
			                    $config['maintain_ratio'] = false;
			                    $this->image_lib->initialize($config);
			    
			                    if (!$this->image_lib->crop())
			                    {
			                        show_error($this->image_lib->display_errors());
			                    }
			    
			                    // Clear lib so we can do some more image processing
			                    $this->image_lib->clear();
			                    // crop image set to center //
			    
			                    //create thumbnail
			    
			                    $config['image_library'] = 'GD2';
			                    $config['source_image'] = $dataupload['full_path'];
			                    $config['new_image'] = $dataupload['full_path'];
			                    $config['quality'] = '75%';
			                    $config['master_dim'] = 'width';
			                    $config['width'] = 150;
			                    $config['height'] = 150;
			    
			                    $this->image_lib->initialize($config);
			                    if (!$this->image_lib->resize())
			                    {
			                        echo $this->image_lib->display_errors();
			                    }
			                    $this->image_lib->clear();
								
								// record to database //
								$this->mem_m->updateUserActive($datainput,$mem['userid']);
								// record to database //
								
								
								/// active member 
								$this->mem_m->activeMember($mem['userid']);		
								
								redirect('/mem/user/panel'); //แสดงหน้า panel					
							}
							else
							{
								//upload รูปไม่ผ่าน
								$this->load->view('mem/activeform_v',$data);
							}
						}
						elseif($cf['p_avatar'] && !$cf['re_p_avatar'])
						{
							//มีหรือไม่มีส่วน avatar ก็ได้
							///upload configuration
				            $config['upload_path'] = './upload/memupload/';
				            $config['allowed_types'] = 'gif|jpg';
				            $config['max_size'] = '500';
				            $config['max_width'] = '2048';
				            $config['max_height'] = '2048';
				            $config['encrypt_name'] = TRUE;
				            $config['remove_spaces'] = TRUE;
				            $this->load->library('upload', $config);
							
							if ($this->upload->do_upload('p_avatar'))
	                		{
	                			//upload รูปผ่าน
			                    $dataupload = $this->upload->data();
			                    $this->load->library('image_lib');
			    
			                    $config['image_library'] = 'GD2';
			                    $config['source_image'] = $dataupload['full_path'];
			                    $config['new_image'] = $dataupload['full_path'];
			                    //upload รูปผ่าน
			                    $datainput['p_avatar'] = $dataupload['file_name'];
			    
			                    // crop image set to center //
			                    if ($dataupload['image_width'] > $dataupload['image_height'])
			                    { // Landscape: Crop left & right
			                        $config['width'] = $dataupload['image_height'];
			                        $config['height'] = $dataupload['image_height'];
			                        $config['x_axis'] = ($dataupload['image_width']-$config['width'])/2;
			                    }
			                    else
			                    { // Portrait: crop top & bottom
			                        $config['width'] = $dataupload['image_width'];
			                        $config['height'] = $dataupload['image_width'];
			                        $config['y_axis'] = ($dataupload['image_height']-$config['height'])/2;
			                    }
			                    $config['maintain_ratio'] = false;
			                    $this->image_lib->initialize($config);
			    
			                    if (!$this->image_lib->crop())
			                    {
			                        show_error($this->image_lib->display_errors());
			                    }
			    
			                    // Clear lib so we can do some more image processing
			                    $this->image_lib->clear();
			                    // crop image set to center //
			    
			                    //create thumbnail
			    
			                    $config['image_library'] = 'GD2';
			                    $config['source_image'] = $dataupload['full_path'];
			                    $config['new_image'] = $dataupload['full_path'];
			                    $config['quality'] = '75%';
			                    $config['master_dim'] = 'width';
			                    $config['width'] = 150;
			                    $config['height'] = 150;
			    
			                    $this->image_lib->initialize($config);
			                    if (!$this->image_lib->resize())
			                    {
			                        echo $this->image_lib->display_errors();
			                    }
			                    $this->image_lib->clear();
								
								// record to database //
								$this->mem_m->updateUserActive($datainput,$mem['userid']);
								// record to database //
								
								
								/// active member 
								$this->mem_m->activeMember($mem['userid']);		
								
								redirect('/mem/user/panel'); //แสดงหน้า panel
							}
							else
							{
								$datainput['p_avatar'] = "";
								// record to database //
								$this->mem_m->signupUser($datainput);
								// record to database //
								
								/// active member 
								$this->mem_m->activeMember($data['mem']['userid']);		
								
								redirect('/mem/user/panel'); //แสดงหน้า panel
							}
						}
						else
						{
							//กรณีที่ไม่มี avatar
							$datainput['p_avatar'] = "";
								// record to database //
								$this->mem_m->signupUser($datainput);
								// record to database //
								
								/// active member 
								$this->mem_m->activeMember($data['mem']['userid']);		
								
								redirect('/mem/user/panel'); //แสดงหน้า panel
						}
						// upload avatar //
					}
				}
				break;
			/******* Form for activate member ********/
			
			/******* resend email for link activate ********/
			case "resendemail":
				$linkdata = $this->uri->segment(4);
						$userid = $this->bee->simpleDecrypt($linkdata);
						$newpass = $this->bee->passwdgen(8);
						$this->mem_m->updatePassword($userid,$newpass);
						
						$profile = $this->mem_m->a_loadProfile($userid);
						//send email to this member
						$this->load->library('phpmailer');
			            $this->phpmailer->IsSendmail();
			            $this->phpmailer->AddReplyTo($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->SetFrom($cf['emailsystem'], $cf['systemname']);
			            $this->phpmailer->AddAddress($datainput['email'], $datainput['username']);
			            $this->phpmailer->Subject = "Account wait for activate FROM ".$cf['systemname'];
			            $this->phpmailer->MsgHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			    	<html xmlns="http://www.w3.org/1999/xhtml">
			    	<head>
			    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			    	<title>Your account wait for activate @ '.$cf["systemname"].'</title>
			    	</head>
			    	
			    	<body>
			    	<p>Please click link for activate your account and full fill form.</p>
					<p>You can click via '.base_url().'mem/sys/activate/'.$linkdata.'</p>
					<p>Username : '.$datainput['username'].'<br />
					Email    : '.$datainput['email'].'<br />
					Password : '.$newpass.'
					</p>
			    	</body>
			    	</html>');
			            if (!$this->phpmailer->Send())
			            {
			                $tmp = "Mailer Error: ".$this->phpmailer->ErrorInfo;
			                mail($cf['emailsystem'], 'mail error FROM '.$cf['systemname'], $tmp);
			
			            } else
			            {
							$data['complete'] = TRUE;
							$data['link'] = base_url()."mem/sys/activate/".$linkdata;
							echo "Resendemail complete";
						}
						/// send email
				
				break;
			/******* resend email for link activate ********/
			
			default:
				$this->load->view('mem/index');
		}
	}
	
	function user()
	{
		$this->load->database();
		$this->load->model('mem/mem_m');
		$this->load->library('Authen');
		// get action //
		$zone = $this->uri->segment(3);
		$cf		= $this->member->memconfig();
		// get action //
		
		switch($zone){
			/******* User Panel ********/
			case "panel":
				if($this->authen->checkauthen()){
					$data['cf'] = $cf;
					$this->load->view('mem/u_index_v',$data);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******* User Panel ********/
			
			/******* View Profile ********/	
			case "view":
				if($this->authen->checkauthen()){
					//load all data of this member
					$data['init'] 		= $this->authen->init();
					$data['profile']	= $this->mem_m->loadProfile($data['init']);
					$data['cf']			= $cf;
					$this->load->view('mem/u_viewprofile_v',$data);
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			/******* View Profile ********/	
			/******* Upload avatar ********/	
			case "upavatar":
				if($this->authen->checkAuthen()){
					///upload configuration
				            $config['upload_path'] = './upload/memupload/';
				            $config['allowed_types'] = 'gif|jpg';
				            $config['max_size'] = '500';
				            $config['max_width'] = '2048';
				            $config['max_height'] = '2048';
				            $config['encrypt_name'] = TRUE;
				            $config['remove_spaces'] = TRUE;
				            $this->load->library('upload', $config);
							
							if ($this->upload->do_upload('userfile'))
	                		{
	                			//upload รูปผ่าน
			                    $dataupload = $this->upload->data();
			                    $this->load->library('image_lib');
			    
			                    $config['image_library'] = 'GD2';
			                    $config['source_image'] = $dataupload['full_path'];
			                    $config['new_image'] = $dataupload['full_path'];
			                    //upload รูปผ่าน
			                    $datainput['p_avatar'] = $dataupload['file_name'];
			    
			                    // crop image set to center //
			                    if ($dataupload['image_width'] > $dataupload['image_height'])
			                    { // Landscape: Crop left & right
			                        $config['width'] = $dataupload['image_height'];
			                        $config['height'] = $dataupload['image_height'];
			                        $config['x_axis'] = ($dataupload['image_width']-$config['width'])/2;
			                    }
			                    else
			                    { // Portrait: crop top & bottom
			                        $config['width'] = $dataupload['image_width'];
			                        $config['height'] = $dataupload['image_width'];
			                        $config['y_axis'] = ($dataupload['image_height']-$config['height'])/2;
			                    }
			                    $config['maintain_ratio'] = false;
			                    $this->image_lib->initialize($config);
			    
			                    if (!$this->image_lib->crop())
			                    {
			                        show_error($this->image_lib->display_errors());
			                    }
			    
			                    // Clear lib so we can do some more image processing
			                    $this->image_lib->clear();
			                    // crop image set to center //
			    
			                    //create thumbnail
			    
			                    $config['image_library'] = 'GD2';
			                    $config['source_image'] = $dataupload['full_path'];
			                    $config['new_image'] = $dataupload['full_path'];
			                    $config['quality'] = '75%';
			                    $config['master_dim'] = 'width';
			                    $config['width'] = 150;
			                    $config['height'] = 150;
			    
			                    $this->image_lib->initialize($config);
			                    if (!$this->image_lib->resize())
			                    {
			                        echo $this->image_lib->display_errors();
			                    }
			                    $this->image_lib->clear();
								
								//get user init
								$mem = $this->authen->init();
								// record to database //
								$this->mem_m->updateUserAvatar($datainput['p_avatar'],$mem['userid']);
								// record to database //
								
							}
				}
				else
				{
					redirect('/pg/sys/logout');
				}
				break;
			/******* Upload avatar ********/
			/******* Edit Profile ********/	
            case "edit":
                if ($this->authen->checkauthen())
                {
                    $this->load->library('form_validation');
                    ///upload configuration
                    $config['upload_path'] = './upload/memupload/';
                    $config['allowed_types'] = 'gif|jpg';
                    $config['max_size'] = '500';
                    $config['max_width'] = '2048';
                    $config['max_height'] = '2048';
                    $config['encrypt_name'] = TRUE;
                    $config['remove_spaces'] = TRUE;
                    $this->load->library('upload', $config);
                    $config = $this->member->Set_ruleeditprofile();
                    $this->form_validation->set_rules($config);
                    // รับค่าทั้งหมด //
                    $cf['username'] = $cf['password'] = $cf['confirmpassword'] = $cf['email'] = TRUE;
                    foreach (explode(' ', 'p_name p_surname p_gender p_birthdate p_married p_address p_city p_state p_zip p_country p_telephone p_mobilephone p_fax p_job p_msn p_hi5 p_facebook p_twitter p_url p_income p_internet p_family p_personalid p_emailnews p_type') as $v)
                    {
                        if ($cf[$v])
                        {
                            $datainput[$v] = $this->input->post($v);
            
                        }
                    }
                    $data = $datainput;
                    // รับค่าทั้งหมด //
                    $data['cf'] = $cf;
                    if ($this->form_validation->run() == FALSE)
                    {
                    	$data['init'] = $this->authen->init();
            			$data = $this->mem_m->profileEdit($data['init']['userid']);
                    	$data['cf'] = $cf;
                        $this->load->view('mem/u_editprofile_v', $data);
                    }
                    else
                    {
                    	$data['init'] = $this->authen->init();
                    	// record to database //
						$this->mem_m->updateProfile($datainput,$data['init']['userid']);
						// record to database //
						$data['profile']	= $this->mem_m->loadProfile($data['init']);
						$data['cf']			= $cf;
						$this->load->view('mem/u_viewprofile_v',$data);
                    }
                    
                }
                else
                {
                    redirect('/mem/sys/logout');
                }
                break;
			/******* Edit Profile ********/	
			
			case "removeavatar":
				if($this->authen->checkauthen()){
					$this->load->library('form_validation');
					$mem = $this->authen->init();
					$config = array(
					               array(
					                     'field'   => 'action',
					                     'label'   => 'action',
					                     'rules'   => 'required'
					                  )
									);
					$this->form_validation->set_rules($config); 
					            							
					
					if ($this->form_validation->run() == FALSE){
						
					}else{
						///check ว่าตอนนี้เก็บรูปอะไรอยู่
						$filename = $this->mem_m->getimage($mem['userid']);
						//delete image
						//$this->load->helper('file');
						//delete_files('uploads/');
						if(strlen($filename)>10){
							unlink('upload/memupload/'.$filename);
						}
						
						$filename = $this->mem_m->removeimage($mem['userid']);
					}
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			
			case "changepass":
				if($this->authen->checkauthen()){
					$this->load->library('form_validation');
		            $config = array(array('field'=>'password', 'label'=>'Password', 'rules'=>'required|min_length[5]|max_length[25]'),
					array(
                     'field'   => 'confirmpassword', 
                     'label'   => 'Confirm Password', 
                     'rules'   => 'required|min_length[5]|max_length[25]|matches[password]'
                  ),array(
                     'field'   => 'password', 
                     'label'   => 'Password', 
                     'rules'   => 'required|min_length[5]|max_length[25]'
                  ));
				  $data['cf'] = $cf;
		            $this->form_validation->set_rules($config);
					if ($this->form_validation->run() == FALSE){
						$this->load->view('mem/u_changpass_v',$data);
					}else{
						
						///update password
						// รับค่าทั้งหมด //
	                    foreach (explode(' ', 'oldpassword password confirmpassword') as $v)
	                    {
	                    	$datainput[$v] = $this->input->post($v);
	                    }
	                    $data = $datainput;
						
	                    // รับค่าทั้งหมด //
						
						// update record //
						$mem = $this->authen->init();
						if($this->mem_m->updatePassword($datainput,$mem))
						{
							$data['cf'] = $cf;
							$data['completed'] = "เปลี่ยนรหัสผ่านเรียบร้อยแล้ว";
							$this->load->view('mem/u_changpass_v',$data);
						}
						else
						{
							$data['cf'] = $cf;
							$data['completed'] = "รหัสผ่านเก่าไม่ถูกต้อง";
							$this->load->view('mem/u_changpass_v',$data);
						}
						// update record //
					}
					
				}
				else
				{
					redirect('/mem/sys/logout');
				}
				break;
			case "delete":
				if($cf['deleteself']){
					$this->load->library('Securimage');
					$this->load->library('session');
					$data['cf'] = $cf;
					$this->load->library('form_validation');
		            $config = array(array('field'=>'p_images', 'label'=>'Secure Code', 'rules'=>'required'));
					$this->form_validation->set_rules($config);
					if ($this->form_validation->run() == FALSE){
						$this->load->view('mem/u_deleteaccount_v',$data);
					}else{
						if(!$this->securimage->check($this->input->post('p_images'))){
							die('securecode wrong');
						}
						$filename = $this->mem_m->getimage($mem['userid']);
						//delete image
						//$this->load->helper('file');
						//delete_files('uploads/');
						if(strlen($filename)>10){
							unlink('upload/memupload/'.$filename);
						}
						
						$filename = $this->mem_m->removeimage($mem['userid']);
						//delete from database
						$mem = $this->authen->init();
						$this->mem_m->deleteUser($mem);
						redirect('/mem/sys/login');
						
					}
				}
				break;
			default:
				$this->load->view('mem/index');
		}
		
	}
	
	function checkMobile($phonenumber){
		if($this->bee->Check_mobilePhone($phonenumber)){
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('checkMobile', 'เบอร์โทรศัพท์มือถือไม่ถูกต้อง');
			return FALSE;
		}

	}
	
	function Check_dateInput($dateinput){
		if($this->bee->Check_dateInput($dateinput)){
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('Check_dateInput', 'วันเกิด ไม่ถูกต้อง');
			return FALSE;
		}
	}
	
	function check_personalid($idinput){
		if($this->bee->Check_personalid($idinput)){
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('check_personalid', 'รหัสบัตรประชาชน ไม่ถูกต้อง');
			return FALSE;
		}
	}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */